#!/usr/bin/env python

import cv2.cv as cv

def is_rect_nonzero(r):
    (_,_,w,h) = r
    return (w > 0) and (h > 0)

class fmUIdemo:

    def __init__(self):
        self.capture = cv.CaptureFromCAM(0) # Capture image from device "0"
        cv.NamedWindow( "fmUIdemo", 1 )
        cv.NamedWindow( "fmProcessed", 1 )
        cv.SetMouseCallback( "fmUIdemo", self.on_mouse)

        self.drag_start = None      # Set to (x,y) when mouse starts drag
        self.track_window = None    # Set to rect when the mouse drag finishes

        print( "Keys:\n"
            "    ESC - quit the program\n"
            "    b - switch to/from backprojection view\n"
            "To initialize tracking, drag across the object with the mouse\n" )

    def on_mouse(self, event, x, y, flags, param):
        if event == cv.CV_EVENT_LBUTTONDOWN:
            self.drag_start = (x, y)
        if event == cv.CV_EVENT_LBUTTONUP:
            self.drag_start = None
            self.track_window = self.selection
            if is_rect_nonzero(self.selection):
                print self.selection
        if self.drag_start:
            xmin = min(x, self.drag_start[0])
            ymin = min(y, self.drag_start[1])
            xmax = max(x, self.drag_start[0])
            ymax = max(y, self.drag_start[1])
            self.selection = (xmin, ymin, xmax - xmin, ymax - ymin)

    def run(self):
        while True:
            frame = cv.QueryFrame( self.capture )

            # If mouse is pressed, highlight the current selected rectangle
            # and recompute the fmProcessed


            c = cv.WaitKey(7) % 0x100
            if c == 27:
                break
            elif c == ord("b"):
                backproject_mode = not backproject_mode
            elif c<> 0xff:
                print c

if __name__=="__main__":
    demo = fmUIdemo()
    demo.run()
    cv.DestroyAllWindows()
